<template>
  <div class="BlogComment-container" ref="BlogComment">
    <MessageArea
      title="评论列表"
      :total="data.total"
      :list="data.rows"
      :isListLoading="isLoading"
      @submit="handleSubmit"
    />
  <div class="BlogComment-end" v-if="!hasMore">已经到底部啦~~</div>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { getComments, postComment } from "@/api/blog.js";
export default {
  mixins: [fetchData({total:0,rows:[]})],
  data(){
    return{
        page:1,
        limit:10
    }
  },
  components: {
    MessageArea,
  },
  created(){
    window.xx = this.fetchMore;
    this.$bus.$on('mainScroll',this.handleScroll)
  },
  destroyed(){
    this.$bus.$off('mainScroll',this.handleScroll)
  },
  computed:{
    hasMore() {
      return this.data.rows.length < this.data.total;   //数据数组的长度 应该要小于 总数的
    }
  },
  methods: {
    async fetchData() {
      return await getComments(this.$route.params.id,this.page,this.limit);
    },
    //加载下一页
    async fetchMore(){
      if(!this.hasMore){
        return; //没有了
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
    //插入博客到formlist
    async handleSubmit(formData,callback){
      const userData = await postComment({
          blogId:this.$route.params.id,
          ...formData
      });
      this.data.rows.unshift(userData);
      this.data.total++;
      callback('评论成功'); //通知formData组件已经处理结束
    },
    //下拉记载
    handleScroll(dom){
      if(this.isLoading || !dom){//加载的时候 或 dom不存在的时候 就不触发了
        return;
      }
      const range = 100;  //给一个范围，到达这一个范围都算到达了底部
      const dec = dom.scrollHeight - dom.scrollTop - dom.clientHeight;
      if(Math.abs(dec) <= range ){
        this.fetchMore();
      }
    }
  },
};
</script>

<style scoped lang='less'>
@import "~@/styles/var.less";
.BlogComment-container {
  margin-top: 50px;
}
.BlogComment-end{
  height: 30px;
  text-align: center;
  font-size: 15px;
  color: @gray;
}
</style>